package cn.wzy.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author nihaowzy
 */
public class MyDataBase {
    private static DataSource ds = null;
    static {
        try(
                InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties")
        ){
            if (null == input){
                new RuntimeException("没有加载druid配置文件");
            }
            Properties prop = new Properties();
            prop.load(input);
            //创建数据连接池
            ds = DruidDataSourceFactory.createDataSource(prop);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 返回数据库连接池
     * @return
     */
    public static DataSource getDs(){
        return ds;
    }

    /**
     * 返回连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws Exception {
        return ds.getConnection();
    }


    @Test
    public void test() throws Exception {
        Connection connection = getConnection();
        System.out.println(connection);
    }
}
